//
//  Exif.swift
//  Exif
//
//  Created by Kazunori Kikuchi on 2017/01/08.
//  Copyright © 2017年 kazunori kikuchi. All rights reserved.
//

import Foundation
import UIKit
import Photos


final class Exif {
   
   private init() {}
   
   static let shared = Exif()
 
    func getExif(_ asset: PHAsset,result: @escaping ((NSDictionary?)->())) {
 
        let imageManager = PHImageManager.default()
        imageManager.requestImageData(for: asset , options: nil, resultHandler:{
            (data, responseString, imageOriet, info) -> Void in
            if let imageData = data as? NSData {
                if let imageSource = CGImageSourceCreateWithData(imageData, nil) {
                    
                    let imageProperties2 = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)! as NSDictionary
                   print("imageProperties2: ", imageProperties2)
                    result(imageProperties2)
                }
            }
           
            
        })
    }
 
    
}


func getDicFromAssets(assets:[PHAsset],result: @escaping (([[String:String]])->())) {
    var dicArr = [[String:String]]()
    
    // 创建调度组
    let workingGroup = DispatchGroup()
    
    for asset in assets {
        // 入组
        workingGroup.enter()
        Exif.shared.getExif(asset) { oridic in
            
            var dic:[String:String] = [:]
            dic.updateValue(UIDevice.current.modelName, forKey: "z_phone_model")
            dic.updateValue("0", forKey: "z_is_take_photo")
            dic.updateValue("", forKey: "z_original_pic_name")
            
            if let gps:NSDictionary = oridic?["{GPS}"] as? NSDictionary {
                let lon = gps["Longitude"] as? Double
                let lat = gps["Latitude"] as? Double
                dic.updateValue(lon.unwrap, forKey: "z_longitude")
                dic.updateValue(lat.unwrap, forKey: "z_latitude")
            }
            
            if let exif:NSDictionary = oridic?["{Exif}"] as? NSDictionary {
                let time = exif["DateTimeOriginal"] as? String
                dic.updateValue(time.unwrap, forKey: "z_original_time")
                
            }
            
            dicArr.append(dic)
            // 出组
            workingGroup.leave()
        }
    }
    // 调度组里的任务都执行完毕
    workingGroup.notify(queue: .main) {
        
        result(dicArr)
        
    }
}
